package org.jpass.dc.compiler;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class CustomClassLoader {
	public static void main(String[] args) {
		String mainClass = new CustomClassLoader().findMainMethod("F:/Exercise/biyesheji/javaparser/bin");
		System.out.println(mainClass);
	}
	public String findMainMethod(String classPath) {
		try {
			URL[] us = { new URL( "file:///"+ classPath)};
			ClassLoader loader = new URLClassLoader(us, Thread.currentThread().getContextClassLoader());
			List<String> classFileList = getClassFileList(classPath);
			for (String classFile : classFileList) {
				String dirPath = classFile.substring(0, classFile.lastIndexOf(File.separator));
				System.out.println(dirPath);
				String className = classFile.substring(classPath.length() + 1, classFile.lastIndexOf(".class"));
				System.out.println(className);
				String name = classFile.substring(classFile.lastIndexOf(File.separator) + 1,
						classFile.lastIndexOf(".class"));
				String separatorStr = "/";
				if ("\\".equals(File.separator)) {
					separatorStr = "\\\\";
				}
				String packageClassName = className.replaceAll(separatorStr, ".");
				Class<?> c = loader.loadClass(packageClassName);
				Object o = c.newInstance();
				Method m = c.getMethod("main", null);
				if (m != null) return (dirPath + "/" + name + ".java");
			}
		} catch (Exception e) {
		    e.printStackTrace();
		}
		
		return null;
	}
	
	public List<String> getClassFileList(String path) {
		ArrayList<String> fileList = new ArrayList<String>();
		return searchClassFiles(path, fileList);
	}
	
	protected List<String> searchClassFiles(String path, List<String> fileList) {
		File dir = new File(path);
        File[] file = dir.listFiles(new MyFilenameFilter());
        if (file == null) 
            return null; 
        for (int i = 0; i < file.length; i++) { 
            if (file[i].isDirectory()) {
            	searchClassFiles(file[i].getAbsolutePath(), fileList); 
            } else {
            	fileList.add(file[i].getAbsolutePath());
            }
        }
        
		return fileList;
	}
}

class  MyFilenameFilter implements FilenameFilter {   
	@Override
	public boolean accept(File dir, String name) {
		if (name.endsWith(".class")) return true;
		return false;
	} 
}
